<?php // Yii::app()->clientScript->registerScriptFile('/js/jquery.autonumeric.js'); ?>
<?php Yii::app()->clientScript->registerScriptFile('/js/jquery.autonumeric/jquery.autonumeric.js'); ?>
<?php $this->pageTitle = 'Compute Commissions'; ?>
<?php
$this->breadcrumbs = array(
	'Receipts' => array('/receipt/index'),
	'#' . $receipt->payment_number => array('/receipt/view', 'id' => $receipt->id),
	($receipt->hasPayableItemsGenerated() ? "Re-Calculate" : "Preview") . " Commissions Calculations"
);
?>
<script>
	var existingPaymentVouchers = <?php echo ($paymentVouchersAssigned) ? $paymentVouchersAssigned : "null"; ?>;
	var editablePolicy = <?php echo $editable; ?>;
</script>
<div class="main-title no-border clearfix">
	<h1 class="float-left"><?php echo($receipt->hasPayableItemsGenerated() ? "View Generated" : "Preview"); ?> Commission Calculations</h1>
	<div class="controls"></div>
</div>
<div class="flat_area">
	<div id="ps-payment-create" class="relative">
		<?php echo CHtml::beginForm(array('receipt/calculateCommissions', 'id' => $receipt->id, 'confirm' => 1), 'post'); ?>
		<?php if (!empty($allPropertyCasesCommissions)): ?>
			<?php foreach ($allPropertyCasesCommissions as $pcIndex => $commissions): ?>
				<div class="grid_14">
					<div class="section">
						<div class="block">
							<div class="table-block">
								<div id="basic_commissions" class="">
									<?php // dump($commissions); ?>
									<?php if (!empty($commissions)): ?>
										<h1>For the property transacted at <?php echo $commissions['totals']['totalBalances']['address']; ?></h1>
										<a class="blue link" href = "<?php echo $this->createUrl('transaction/default/' . $commissions['totals']['totalBalances']['property_case_id'] . '#Commissions'); ?>">View Transaction</a>
										<?php foreach ($commissions as $agentId => $agentCommissions): ?>
											<?php if ($agentId != 'totals'): ?>
												<?php if (!empty($agentCommissions['commissions'])): ?>
													<table class="form-table
													<?php echo($agentCommissions['starting_scores'] ? 'box' : '' ); ?>
													<?php echo(in_array($agentId, $toPromote) && !$receipt->hasPayableItemsGenerated() ? ' crossed' : '' ); ?>" 
														   width="100%">

														<!--This row displays the name and designation-->
														<tr>
															<?php if ($agentCommissions['starting_scores']) : ?>
																<td scope="row" class="blue bold">
																	<?php echo($agentCommissions['agent_role'] == 'Main' ? 'Closing Agent: ' : 'Co-broker: '); ?> 
																	<span id="agent-name"><?php echo $agentCommissions['agent_name']; ?></span> (<?php echo $agentCommissions['agent_designation']; ?>)
																</td>
															<?php elseif (!isset($agentCommissions['external_agency'])): ?>
																<td scope="row" class="blue overrider">
																	<?php echo $agentCommissions['agent_name']; ?> (<?php echo $agentCommissions['agent_designation']; ?>)
																</td>
															<?php endif; ?>
															<td></td>
															<td colspan="2" class="promote"><?php echo(in_array($agentId, $toPromote) && !$receipt->hasPayableItemsGenerated() ? 'Based on promotion criteria settings, this salesperson was already qualified for promotion to ' . $agentCommissions['recommended_desig_name'] . $agentCommissions['recommended_message'] : '' ); ?></td>
														</tr>
														<?php if (strpos($agentCommissions['recommended_message'], 'yet') !== false && !$receipt->hasPayableItemsGenerated()) : ?>
															<tr>
																<td colspan="4" class="promote align-right">
																	<a id="promote-link" class="blue link" 
																	   href="<?php
								echo $this->createUrl('/manage/users/promote', array(
									'id' => $agentCommissions['user_id'],
									'date' => $commissions['totals']['totalBalances']['commission_date'],
									'desigId' => $agentCommissions['recommended_desig_id'],
									'receiptId' => $receipt->id));
															?>">
																		<u>[Promote]</u>
																	</a>
																</td>
															</tr>
														<?php endif; ?>



														<!--This row displays the structure name(basic or override), co-broker gross amounts, and percents applied-->
														<?php foreach ($agentCommissions['commissions'] as $commIndex => $commissionDetails): ?>
															<tr>
																<?php if ($commissionDetails['comm_type'] == 'basic'): ?>
																	<td width="50%" class="valign-top">
																		<?php echo $commissionDetails['basicStructureName']; ?>
																	</td>
																<?php elseif ($commissionDetails['comm_type'] == 'overriding'): ?>
																	<td width="50%" class="valign-top overrider">
																		<?php echo $commissionDetails['overrideStructureName']; ?> : Tier <?php echo $commissionDetails["tier"] . ' of co-broker: ' . $commissionDetails['closing_downline_name']; ?>
																	</td>
																<?php elseif ($commissionDetails['comm_type'] == 'management_overriding'): ?>
																	<td width="50%" class="valign-top">
																		<?php echo $commissionDetails['overrideStructureName']; ?> : Management Override of co-broker <?php echo $commissionDetails['closing_downline_name']; ?>
																	</td>
																<?php elseif ($commissionDetails['comm_type'] == 'referrer'): ?>
																	<td width="50%" class="valign-top">
																		<?php echo $commissionDetails['structureName']; ?> : Referrer of co-broker <?php echo $commissionDetails['closing_referee_name']; ?>
																	</td>
																<?php endif; ?>

																<td>
																</td>




																<!--This column shows the formula/calculations-->
																<td class="align-right ">
																	<?php if ($commissionDetails['comm_type'] == 'basic' && !empty($commissionDetails["split"])): ?>
																		<div class="basic-comm-details">
																			<?php echo CHtml::hiddenField('allPropertyCasesCommissions[' . $pcIndex . '][' . $agentId . '][commissions][' . $commIndex . '][gross]', $commissionDetails["steppedVolume"], array('class' => 'input-gross')) ?>
																			<?php if ($commissionDetails["split"]["method"] == 'percentage'): ?>
																				<?php echo Yii::app()->numberFormatter->formatCurrency($commissionDetails["steppedVolume"], 'SGD') . ' x '; ?>
																				<?php echo CHtml::textField('allPropertyCasesCommissions[' . $pcIndex . '][' . $agentId . '][commissions][' . $commIndex . '][percent]', number_format($commissionDetails['split_method_agent'], 2), array('class' => 'input-percent')); ?> %
																			<?php endif; ?>
																			<?php if ($commissionDetails["split"]["method"] == 'percentage_min'): ?>
																				<?php echo Yii::app()->numberFormatter->formatCurrency($commissionDetails["steppedVolume"], 'SGD') . ' x '; ?>  
																				<?php echo CHtml::textField('allPropertyCasesCommissions[' . $pcIndex . '][' . $agentId . '][commissions][' . $commIndex . '][percent]', number_format($commissionDetails['split_method_agent'], 2), array('class' => 'input-percent')); ?> % 
																				<span class="comm-remarks">
																					<?php echo ': Minimum amount (' . Yii::app()->numberFormatter->formatCurrency($commissionDetails["split"]["agentAmount"], 'SGD') . ')'; ?>  
																				</span>
																			<?php endif; ?>
																			<?php if ($commissionDetails["split"]["method"] == 'percentage_max'): ?>
																				<?php echo Yii::app()->numberFormatter->formatCurrency($commissionDetails["steppedVolume"], 'SGD') . ' x '; ?>
																				<?php echo CHtml::textField('allPropertyCasesCommissions[' . $pcIndex . '][' . $agentId . '][commissions][' . $commIndex . '][percent]', number_format($commissionDetails['split_method_agent'], 2), array('class' => 'input-percent')); ?> % 
																				<span class="comm-remarks">
																					<?php echo ': Maximum amount (' . Yii::app()->numberFormatter->formatCurrency($commissionDetails["split"]["agentAmount"], 'SGD') . ')'; ?>
																				</span>
																			<?php endif; ?>
																			<?php if ($commissionDetails["split"]["method"] == 'fixed_dollar'): ?>
																				<?php echo Yii::app()->numberFormatter->formatCurrency($commissionDetails["steppedVolume"], 'SGD') . ' : '; ?>  
																				<?php echo 'Fixed amount (' . Yii::app()->numberFormatter->formatCurrency($commissionDetails["split"]["agentAmount"], 'SGD') . ')'; ?>  
																			<?php endif; ?>
																			<?php if ($commissionDetails["split"]["agentRider"] > 0): ?>
																				<span class="comm-remarks">	
																					<?php echo ' + (Agent Rider : ' . Yii::app()->numberFormatter->formatCurrency($commissionDetails["split"]["agentRider"], 'SGD') . ')'; ?>  
																				</span>
																			<?php endif; ?>
																		</div>
																	<?php endif; ?>

																	<?php if ($commissionDetails['comm_type'] == 'overriding' && !empty($commissionDetails["strategy"])): ?>
																		<div>
																			<?php echo CHtml::hiddenField('allPropertyCasesCommissions[' . $pcIndex . '][' . $agentId . '][commissions][' . $commIndex . '][gross]', $commissionDetails["input_amount"], array('class' => 'input-gross')) ?>
																			<?php if ($commissionDetails["strategy"]["amountType"] == 'fixed_percentage'): ?>
																				<?php echo Yii::app()->numberFormatter->formatCurrency($commissionDetails["input_amount"], 'SGD') . ' x '; ?>  
																				<?php // echo $commissionDetails['strategy']['amount'] . '%'; ?>
																				<?php echo CHtml::textField('allPropertyCasesCommissions[' . $pcIndex . '][' . $agentId . '][commissions][' . $commIndex . '][percent]', number_format($commissionDetails['strategy']['amount'], 2), array('class' => 'input-percent')); ?> %
																			<?php endif; ?>
																			<?php if ($commissionDetails["strategy"]["amountType"] == 'fixed_dollar'): ?>
																				<?php echo Yii::app()->numberFormatter->formatCurrency($commissionDetails["input_amount"], 'SGD') . ' : '; ?> 
																				<?php echo 'Fixed amount (' . Yii::app()->numberFormatter->formatCurrency($commissionDetails["overriding"], 'SGD') . ')'; ?>  
																			<?php endif; ?>
																		</div>
																	<?php endif; ?>

																	<?php if ($commissionDetails['comm_type'] == 'management_overriding' && $commissionDetails["overriding"] > 0) : ?>
																		<div>
																			<?php echo CHtml::hiddenField('allPropertyCasesCommissions[' . $pcIndex . '][' . $agentId . '][commissions][' . $commIndex . '][gross]', $commissionDetails["input_amount"], array('class' => 'input-gross')) ?>
																			<?php echo Yii::app()->numberFormatter->formatCurrency($commissionDetails["input_amount"], 'SGD') . ' x '; ?> 
																			<?php // echo $commissionDetails["percent"] . '%'; ?>
																			<?php echo CHtml::textField('allPropertyCasesCommissions[' . $pcIndex . '][' . $agentId . '][commissions][' . $commIndex . '][percent]', number_format($commissionDetails["percent"], 2), array('class' => 'input-percent')); ?> %
																		</div>
																	<?php endif; ?>

																	<?php if ($commissionDetails['comm_type'] == 'referrer'): ?>
																		<div>
																			<?php echo CHtml::hiddenField('allPropertyCasesCommissions[' . $pcIndex . '][' . $agentId . '][commissions][' . $commIndex . '][gross]', $commissionDetails["input_amount"], array('class' => 'input-gross')) ?>
																			<?php if (strpos($commissionDetails["structureType"], 'management') === false): ?>	
																				<?php if ($commissionDetails["strategyRecommender"]["amountType"] == 'fixed_percentage'): ?>
																					<?php echo Yii::app()->numberFormatter->formatCurrency($commissionDetails["input_amount"], 'SGD') . ' x '; ?>  
																					<?php echo CHtml::textField('allPropertyCasesCommissions[' . $pcIndex . '][' . $agentId . '][commissions][' . $commIndex . '][percent]', number_format($commissionDetails['strategyRecommender']['amount'], 2), array('class' => 'input-percent')); ?> %
																				<?php endif; ?>
																				<?php if ($commissionDetails["strategyRecommender"]["amountType"] == 'fixed_dollar'): ?>
																					<?php echo Yii::app()->numberFormatter->formatCurrency($commissionDetails["input_amount"], 'SGD') . ' : '; ?> 
																					<?php echo 'Fixed amount (' . Yii::app()->numberFormatter->formatCurrency($commissionDetails["referral_share"], 'SGD') . ')'; ?>  
																				<?php endif; ?>
																			<?php else: ?>
																				<?php echo Yii::app()->numberFormatter->formatCurrency($commissionDetails["input_amount"], 'SGD') . ' x '; ?> 
																				<?php echo CHtml::textField('allPropertyCasesCommissions[' . $pcIndex . '][' . $agentId . '][commissions][' . $commIndex . '][percent]', number_format($commissionDetails['recommender_percent'], 2), array('class' => 'input-percent')); ?> %
																			<?php endif; ?>
																		</div>
																	<?php endif; ?>
																</td>



																<!--This column totals the amounts for each co-broker/overrider/referrer-->
																<td width="20%" class="align-right ">
																	<?php if ($commissionDetails['comm_type'] == 'basic' && !empty($commissionDetails["split"])): ?>
																		<div>
																			<?php // echo Yii::app()->numberFormatter->formatCurrency($commissionDetails["split"]["agentAmount"] + $commissionDetails["split"]["agentRider"], 'SGD'); ?>
																			<?php echo CHtml::textField('allPropertyCasesCommissions[' . $pcIndex . '][' . $agentId . '][commissions][' . $commIndex . '][net]', number_format($commissionDetails["split"]["agentAmount"] + $commissionDetails["split"]["agentRider"], 2), array('class' => 'input-value')); ?>
																		</div>
																	<?php endif; ?>
																	<?php if (strpos($commissionDetails['comm_type'], 'overriding') !== false && $commissionDetails['overriding'] > 0): ?>
																		<div>
																			<?php // echo Yii::app()->numberFormatter->formatCurrency($commissionDetails["overriding"], 'SGD'); ?>
																			<?php echo CHtml::textField('allPropertyCasesCommissions[' . $pcIndex . '][' . $agentId . '][commissions][' . $commIndex . '][net]', number_format($commissionDetails["overriding"], 2), array('class' => 'input-value')); ?>
																		</div>
																	<?php endif; ?>
																	<?php if ($commissionDetails['comm_type'] == 'referrer' && $commissionDetails["referral_share"] > 0): ?>
																		<div>
																			<?php // echo Yii::app()->numberFormatter->formatCurrency($commissionDetails["referral_share"], 'SGD'); ?>
																			<?php echo CHtml::textField('allPropertyCasesCommissions[' . $pcIndex . '][' . $agentId . '][commissions][' . $commIndex . '][net]', number_format($commissionDetails["referral_share"], 2), array('class' => 'input-value')); ?>
																		</div>
																	<?php endif; ?>
																</td>
															</tr>

														<?php endforeach; ?>
														<?php if (!isset($agentCommissions['external_agency'])): ?>
															<tr>
																<td colspan="3"></td>
																<td class="align-right internal agent-total">
																	<strong>$<span><?php echo $this->calculateAgentTotal($agentCommissions); ?></span></strong>
																</td>
															</tr>
														<?php endif; ?>

													</table>
												<?php endif; ?>
											<?php endif; ?>
										<?php endforeach; ?>
									<?php endif; ?>
									<table class="form-table box">
										<tr>
											<td class="align-right">Total receipt amount</td>
											<td colspan="2"></td>
											<td class="align-right amount-received">
												<strong>$<span class="amount-received"><?php echo number_format($commissions['totals']['amountAppliedForInvoice'], 2, '.', ''); ?></span></strong>
											</td>
										</tr>
										<tr>
											<td class="align-right internal" colspan="2">Less: Total for internal agents</td>
											<td class="align-right internal all-agent-total">
												<strong>$<span class="all-agent-total"><?php echo number_format($commissions['totals']['totalForInternalAgents'], 2, '.', ''); ?></span></strong>
												<?php echo CHtml::hiddenField('allPropertyCasesCommissions[' . $pcIndex . '][totals][totalForInternalAgents]', $commissions['totals']['totalForInternalAgents'], array('class' => 'input-all-agent-total')); ?>
											</td>

										</tr>
										<tr>
											<td class="align-right" colspan="2">Less: Total for external agents</td>
											<td class="align-right external-agent-total">
												<strong>$<span class="external-agent-total"><?php echo number_format($commissions['totals']['totalForExternalAgents'], 2, '.', ''); ?></span></strong>
											</td>

										</tr>
										<tr>
											<td class="align-right" colspan="2">Less: Total for external parties</td>
											<td class="align-right external-party-total">
												<strong>$<span class="external-party-total"><?php echo number_format($commissions['totals']['totalForExtParties'], 2, '.', ''); ?></span></strong>
											</td>

										</tr>
										<tr>
											<td class="align-right" colspan="2">Less: Amount reserved for GST</td>
											<td class="align-right amount-reserved-for-gst">
												<strong>$<span class="amount-reserved-for-gst"><?php echo number_format($commissions['totals']['totalReservedForGST'], 2, '.', ''); ?></span></strong>
											</td>
										</tr>
										<tr>
											<td class="align-right"><strong>Balance for <?php echo Yii::app()->user->model->agency->name; ?></strong></td>
											<td colspan="2"></td>
											<td class="align-right agency-balance">
												<strong><?php echo Yii::app()->numberFormatter->formatCurrency($commissions['totals']['balanceForAgency'], '$'); ?></strong>
												<?php echo CHtml::hiddenField('allPropertyCasesCommissions[' . $pcIndex . '][totals][balanceForAgency]', $commissions['totals']['balanceForAgency'], array('class' => 'input-agency-balance')); ?>
											</td>
										</tr>
									</table>
								</div>
							</div>
						</div>
					</div>
				</div>
			<?php endforeach; ?>
		<?php endif; ?>
		<div class="grid_16">
			<a id = "back" class = "link-button with-icon" href = "<?php echo $this->createUrl('/receipt/view', array('id' => $receipt->id)); ?>">
				Back to Receipt
			</a>	
			<?php $btnLabel = $receipt->hasPayableItemsGenerated() ? 'Re-Generate Payable Items' : 'Generate Payable Items' ?>
			<?php $btnColor = $receipt->hasPayableItemsGenerated() ? 'red no-margin' : 'green no-margin' ?>
			<?php echo GxHtml::submitButton($btnLabel, array('id' => 'generate', 'name' => 'confirm', 'class' => $btnColor)); ?>	
		</div>
		<?php echo CHtml::endForm(); ?>
	</div>
</div>

<?php $this->renderPartial('_dialog_genpayableitem_deny'); ?>
